DECLARE SUB PrintResult (digits$, guess$)
DECLARE FUNCTION ChooseNumber$ (LENGTH AS INTEGER)
RANDOMIZE TIMER

CONST NUMBERLENGTH = 4

CLS
number$ = ChooseNumber$(NUMBERLENGTH)
count = 1

DO
  INPUT "Enter number: ", guess$
  IF guess$ = "" THEN EXIT DO

  IF LEN(guess$) <> NUMBERLENGTH THEN
    PRINT "Number must be" + STR$(NUMBERLENGTH) + " digits"
  ELSE
    IF guess$ = number$ THEN
      PRINT "You got it in" + STR$(count) + " tries"
      EXIT DO
    ELSE
      count = count + 1
      PrintResult number$, guess$
    END IF
  END IF
LOOP


FUNCTION ChooseNumber$ (LENGTH AS INTEGER)
  digits$ = ""

  i = 1
  DO WHILE LEN(digits$) < LENGTH
    found = 0
    d$ = MID$(STR$(1 + INT(RND * 9)), 2, 1)
    FOR j = 1 TO LEN(digits$)
      IF MID$(digits$, j, 1) = d$ THEN
        found = 1
        EXIT FOR
      END IF
    NEXT
    IF found = 0 THEN digits$ = digits$ + d$
  LOOP

  ChooseNumber$ = digits$
END FUNCTION

SUB PrintResult (digits$, guess$)
  buls = 0
  hits = 0
  FOR i = 1 TO LEN(guess$)
    g$ = MID$(guess$, i, 1)
    d$ = MID$(digits$, i, 1)
    IF g$ = d$ THEN
      MID$(guess$, i, 1) = "*"
      buls = buls + 1
    END IF
  NEXT
  FOR i = 1 TO LEN(guess$)
    g$ = MID$(guess$, i, 1)
    IF g$ <> "*" THEN
      FOR j = 1 TO LEN(digits$)
        d$ = MID$(digits$, j, 1)
        IF g$ = d$ THEN hits = hits + 1
      NEXT
    END IF
  NEXT

  PRINT "Buls:" + STR$(buls) + ", Hits:" + STR$(hits)
END SUB

